package com.omenkk.juc.ReentrantLock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class demo6 {
    //线程1输出a五次，线程b输出b五次，线程c输出c五次 按照 abcabcabcabcabc
    public static void main(String[] args) {
//        m m=new m(1,5);
//        new Thread(()->{
//            m.print(1,2,"a");
//        }).start();
//        new Thread(()->{
//            m.print(2,3,"b");
//        }).start();
//        new Thread(()->{
//            m.print(3,1,"c");
//        }).start();

        AwaitSignal awaitSignal=new AwaitSignal(5);
        Condition c1=awaitSignal.newCondition();
        Condition c2=awaitSignal.newCondition();
        Condition c3=awaitSignal.newCondition();
        new Thread(()->{
            awaitSignal.print("a",c1,c2);
        }).start();
        new Thread(()->{
            awaitSignal.print("b",c2,c3);
        }).start();
        new Thread(()->{
            awaitSignal.print("c",c3,c1);
        }).start();
        awaitSignal.start(c1);
    }
}
//synchronized版本的控制顺序输出
class m{
    private int flag;//当前输出的是第i个线程
    private int loopNumber;//输出几次

    public m(int flag,int loopNumber) {
        this.flag = flag;
        this.loopNumber = loopNumber;
    }
            public void print(int curFlag,int nextFlag,String str){
                for(int i=0;i<loopNumber;i++){
                    synchronized (this){
                        while(curFlag!=flag){
                            try{
                                this.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        System.out.println(str);
                        flag=nextFlag;
                        this.notifyAll();
                    }
                }
        }


}
@Slf4j
class AwaitSignal extends ReentrantLock{
    private int loopNumber;

    public AwaitSignal(int loopNumber) {
        this.loopNumber = loopNumber;
    }

    public void start(Condition cur){
        this.lock();
        try{
            log.debug("开始打印");
            cur.signalAll();
        } finally {
            this.unlock();
        }
    }
    public void print(String str, Condition cur,Condition next){
        for(int i=0;i<loopNumber;i++){
            this.lock();
            try{
                cur.await();
                System.out.println(str);
                next.signalAll();
            }catch (InterruptedException e){
                e.printStackTrace();
            }finally {
                this.unlock();
            }
        }
    }
}
